//
//  SignalDetailViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/28/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "SignalDetailViewController.h"

@interface SignalDetailViewController ()

@end

@implementation SignalDetailViewController
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;


static const int TIMING_RING1_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING1_GRAPH_POSITION_Y=300;
static const int TIMING_RING1_GRAPH_HEIGHT=20;
static const int TIMING_RING2_GRAPH_INITIAL_POSITION_X=10;
static const int TIMING_RING2_GRAPH_POSITION_Y=330;
static const int TIMING_RING2_GRAPH_HEIGHT=20;

@synthesize timeAdjustButton = _timeAdjustButton;
@synthesize timingPattern=_timingPattern;
@synthesize subSystem=_subSystem;
@synthesize agency=_agency;
@synthesize signal=_signal;
@synthesize signalList=_signalList;
@synthesize signalIndex=_signalIndex;
@synthesize SignalNameLabel=_SignalNameLabel;
@synthesize CycleLengthLabel=_CycleLengthLabel;
@synthesize OffsetLabel=_OffsetLabel;
@synthesize SignalTimerLabel=_SignalTimerLabel;
//@synthesize Ring1CurrentPhaseLabel=_Ring1CurrentPhaseLabel;
//@synthesize Ring1NextPhaseLabel=_Ring1NextPhaseLabel;
//@synthesize Ring2CurrentPhaseLabel=_Ring2CurrentPhaseLabel;
//@synthesize Ring2NextPhaseLabel=_Ring2NextPhaseLabel;
@synthesize LastSignalButton=_LastSignalButton;
@synthesize NextSignalButton=_NextSignalButton;

@synthesize timingRing1GraphPositionX=_timingRing1GraphPositionX;
@synthesize timingRing2GraphPositionX=_timingRing2GraphPositionX;
@synthesize timer=_timer;
@synthesize labelList=_labelList;
@synthesize mainCountDownLabel = _mainCountDownLabel;
@synthesize cycleLabel=_cycleLabel;
@synthesize offsetPhaseTime=_offsetPhaseTime;
//@synthesize signalMovementImageManager=_signalMovementImageManager;
@synthesize dynamicIntersectionView=_dynamicIntersectionView;
@synthesize lastMainCountDownNumber=_lastMainCountDownNumber;
@synthesize automaticPlayOrNot=_automaticPlayOrNot;
@synthesize locationManager=_locationManager;
@synthesize automaticDirection=_automaticDirection;
@synthesize intersection=_intersection;
@synthesize adjustTimeBool=_adjustTimeBool;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
        return self;
}

- (void)viewDidLoad
{
    counter=0;
    [super viewDidLoad];
    self.adjustTimeBool=NO;
    self.timeAdjustButton.layer.cornerRadius = 5;
    self.view.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.view.opaque = NO;
//    self.view.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];
    // Do any additional setup after loading the view from its nib.
    self.offsetPhaseTime=0;
    
    int i=0;
    for (i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        if ([self.signal.offsetPhase isEqualToString:phase.phaseID]) {
            if ([self.signal.offsetBorE isEqualToString:@"Green End"]) {
                self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                
            }
            break;
        }
        self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
    }
    if (i>=self.signal.ring1.phaseList.count) {
        self.offsetPhaseTime=0;
        for (i=0; i<self.signal.ring2.phaseList.count; i++) {
            SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
            if ([self.signal.offsetPhase isEqualToString:phase.phaseID]) {
                if ([self.signal.offsetBorE isEqualToString:@"Green End"]) {
                    self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                    
                }
                break;
            }
            self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        }
        if (i>=self.signal.ring2.phaseList.count) {
            self.offsetPhaseTime=0;
        }
    }
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] offSet:([self.signal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    if (self.SignalNameLabel) {
        self.SignalNameLabel.text=self.signal.signalName;
    }
    if (self.CycleLengthLabel) {
        self.CycleLengthLabel.text=[NSString stringWithFormat:@"Cycle Length: %@",self.signal.cycleLength];
    }
    if (self.OffsetLabel) {
        self.OffsetLabel.text=[NSString stringWithFormat:@"Offset: %@",self.signal.offset];
    }
    if (self.SignalTimerLabel) {
        
        
        self.SignalTimerLabel.text=[NSString stringWithFormat:@"Controller Timer: %d/%@",controllerTimer,self.signal.cycleLength];
    }
    if (!_cycleLabel) {
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        
        UILabel * backgroundLabel=[[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY-11,300,62)] autorelease];
        backgroundLabel.backgroundColor=[UIColor lightGrayColor];
        backgroundLabel.layer.borderColor=[UIColor grayColor].CGColor;
        backgroundLabel.layer.borderWidth=1;
        [self.view addSubview:backgroundLabel];
        int cycleLabelLength;
        if ([self.signal.cycleLength intValue]==0) {
            cycleLabelLength=0;
        }else
        {
            cycleLabelLength=controllerTimer*300/[self.signal.cycleLength intValue];
        }
        
       _cycleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY-10,cycleLabelLength,5)];
        
        _cycleLabel.backgroundColor = [UIColor blueColor];
        _cycleLabel.textColor=[UIColor darkGrayColor];
        [self.view addSubview:_cycleLabel];
        
        
           
    }
//   [self updateRealTimeInformation];    
    if (!_labelList) {
        _labelList=[[NSMutableArray alloc] init];
    }
    [self updateLabels];
    UIPanGestureRecognizer *dragGesture = [[[UIPanGestureRecognizer alloc] 
                                            initWithTarget:self 
                                            action:@selector(pageSlided:)] autorelease];
    
	[self.view addGestureRecognizer:dragGesture];
    
    if (!_dynamicIntersectionView) {
        _dynamicIntersectionView=[[DynamicIntersectionView alloc] initWithSignal:self.signal];
    }
    
//    for (int i=0; i<self.signalMovementImageManager.ring1ImageList.count; i++) {
//        [self.view addSubview:[self.signalMovementImageManager.ring1ImageList objectAtIndex:i]];
//    }
//    for (int i=0; i<self.signalMovementImageManager.ring2ImageList.count; i++) {
//        [self.view addSubview:[self.signalMovementImageManager.ring2ImageList objectAtIndex:i]];
//    }
    [self.view addSubview:self.dynamicIntersectionView];
    [self.view sendSubviewToBack:self.dynamicIntersectionView];
    
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    
    UIBarButtonItem *playButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startStopAction:)] autorelease];
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    BOOL automaticPlayOrNot= [userDefaults boolForKey:@"automaticPlayOrNot"];
//    if (automaticPlayOrNot) {
//        [playButton setStyle:UIBarButtonSystemItemPause];
//        [self.locationManager startUpdatingLocation];
//        self.automaticPlayOrNot=YES;
//    }else
//    {
//        [playButton setStyle:UIBarButtonSystemItemPlay];
//        [self.locationManager stopUpdatingLocation];
//        self.automaticPlayOrNot=NO;
//    }
    
    
//    UIBarButtonItem *timeSpaceButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(goToTimeSpace:)] autorelease];
    CustomizedBarButtonItem *timeSpaceButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIcon.png"] target:self action:@selector(goToTimeSpace:)] autorelease];
//    [playButton setStyle:UIBarButtonSystemItemPause];
    
    CustomizedBarButtonItem *timeSpaceHistoryButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIconHistory.png"] target:self action:@selector(goToTimeSpaceHistory:)] autorelease];
    
    
    UIBarButtonItem *editSignalButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(goToEditSignal:)] autorelease];
    
//    UIBarButtonItem *timeSpaceHistoryButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(goToTimeSpaceHistory:)] autorelease];
    
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,playButton,space,timeSpaceButton,space,timeSpaceHistoryButton,space,editSignalButton,nil ];

    [self initRealTimeInformation];
    {
        if (!self.locationManager)
            self.locationManager = [[CLLocationManager alloc] init] ;
        
        self.locationManager.delegate = self;
        [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        // Set a movement threshold for new events.
        //        self.locationManager.distanceFilter = 10;
        //        if (self.automaticPlayOrNot) {
        //            [self.locationManager startUpdatingLocation];
        //        }
        
        
    }
    
    
}

- (void)viewDidUnload
{
    [self setTimingPattern:nil];
    [self setSubSystem:nil];
    [self setAgency:nil];
    [self setSignal:nil];
    [self setSignalList:nil];
    [self setSignalNameLabel:nil];
    [self setCycleLengthLabel:nil];
    [self setOffsetLabel:nil];
    [self setSignalTimerLabel:nil];
//    [self setRing1CurrentPhaseLabel:nil];
//    [self setRing1NextPhaseLabel:nil];
//    [self setRing2CurrentPhaseLabel:nil];
//    [self setRing2NextPhaseLabel:nil];
    [self setLastSignalButton:nil];
    [self setNextSignalButton:nil];
    [self setLocationManager:nil];
    [self setIntersection:nil];
    
    
    self.timer=nil;
    self.labelList=nil;
    self.cycleLabel=nil;
//    self.signalMovementImageManager=nil;
    self.dynamicIntersectionView=nil;
    [self setMainCountDownLabel:nil];
    [self setTimeAdjustButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}





- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [_timingPattern release];
    [_subSystem release];
    [_agency release];
    [_signal release];
    [_signalList release];
    [_SignalNameLabel release];
    [_CycleLengthLabel release];
    [_OffsetLabel release];
    [_SignalTimerLabel release];
    [_intersection release];
//    [_Ring1CurrentPhaseLabel release];
//    [_Ring1NextPhaseLabel release];
//    [_Ring2CurrentPhaseLabel release];
//    [_Ring2NextPhaseLabel release];
    [_LastSignalButton release];
    [_NextSignalButton release];
    
    [_timer release];
    [_labelList release];
    [_cycleLabel release];
//    [_signalMovementImageManager release];
    [_dynamicIntersectionView release];
    [_mainCountDownLabel release];
    [_locationManager release];
    [_timeAdjustButton release];
    [super dealloc];
}

- (id) initWithNibNameAndSignal:(NSString *)nibName agency:(Agency *)agency subSystem:(SubSystem *)subSystem timingPattern:(TimingPattern *)timingPattern signal:(Signal *)signal bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.timingPattern=timingPattern;
    self.subSystem=subSystem;
    self.agency=agency;
    self.signal=signal;
    self.signalList=[XMLParser getSignalList:agency.agencyID subSystemID:subSystem.subSystemID timingPatternID:timingPattern.timingPatternID];
    for (int i=0; i<self.signalList.count; i++) {
        if ([signal.signalID isEqualToString:[[self.signalList objectAtIndex:i] signalID]]) {
            self.signalIndex=i;
            break;
        }
    }
    return self;
}
- (id) initWithNibNameAndSignal:(NSString *)nibName agency:(Agency *)agency subSystem:(SubSystem *)subSystem timingPattern:(TimingPattern *)timingPattern signalList:(NSArray *)signalList signalIndex:(int)signalIndex automaticPlayOrNot:(BOOL)automaticPlayorNot bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.timingPattern=timingPattern;
    self.subSystem=subSystem;
    self.agency=agency;
    self.signal=[signalList objectAtIndex:signalIndex];
    self.signalList=signalList;
    self.signalIndex=signalIndex;
    self.intersection=[XMLParser getIntersection:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    self.automaticPlayOrNot=automaticPlayorNot;
    return self;
}



- (void) updateLabels
{
    for (UILabel *label in self.labelList) {
        [label removeFromSuperview];
    }
    self.labelList=[[[NSMutableArray alloc] init] autorelease];
    self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
    self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
    int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
    int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
    
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    int ring1BarrierTime=0;
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring1BarrierTime=ring1BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring1BarrierTime=ring1BarrierTime+self.timingRing1GraphPositionX;
    int ring2BarrierTime=0;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==1) {
            int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
            int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
            int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
            ring2BarrierTime=ring2BarrierTime+greenPhaseLength+yellowPhaseLength+allRedPhaseLength;
        }
    }
    ring2BarrierTime=ring2BarrierTime+self.timingRing2GraphPositionX;
    double barrierTime=0;
    if (ring1BarrierTime>=ring2BarrierTime) {
        barrierTime=ring1BarrierTime;
    }else{
        barrierTime=ring2BarrierTime;
    }
    int barrierPositionX=barrierTime;
    
    for (int i=0; i<ring1PhaseList.count; i++) {
        SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing1GraphPositionX<barrierPositionX) {
            self.timingRing1GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
        int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
        int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
        [greenLabel setTag:(100+i)];
        
        greenLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture =
        [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)] autorelease];
        [greenLabel addGestureRecognizer:tapGesture];
        
        
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];  
        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];      
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];      
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing1GraphPositionX=self.timingRing1GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight+10)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    
    
    timingGraphPositionY=TIMING_RING2_GRAPH_POSITION_Y;
    timingGraphHeight=TIMING_RING2_GRAPH_HEIGHT;
    for (int i=0; i<ring2PhaseList.count; i++) {
        SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
        if ([phase.barrier intValue]==2 && self.timingRing2GraphPositionX<barrierPositionX) {
            self.timingRing2GraphPositionX=barrierPositionX;
        }
        int greenPhaseLength=round(300*[phase.greenTime doubleValue]/[self.signal.cycleLength intValue]);
        int yellowPhaseLength=round(300*[phase.yellowTime doubleValue]/[self.signal.cycleLength intValue]);
        int allRedPhaseLength=round(300*[phase.allRedTime doubleValue]/[self.signal.cycleLength intValue]);
        UILabel *greenLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,greenPhaseLength,timingGraphHeight)] autorelease];
//        greenLabel.tag=200+i;
        [greenLabel setTag:200+i];
        greenLabel.text =[phase.phaseID stringByAppendingString:phase.phaseMovement];
        greenLabel.font = [UIFont boldSystemFontOfSize:12.0];
        greenLabel.textAlignment = UITextAlignmentCenter;
        greenLabel.backgroundColor = [UIColor greenColor];
        greenLabel.textColor=[UIColor darkGrayColor];  
        [self addLabelResponder:greenLabel];
        [self.labelList addObject:greenLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        
        //        [self.labelList addObject:greenLabel];
        //        UILabel * tempLabel=[self.labelList objectAtIndex:self.labelList.count-1];
        //        [[self.labelList objectAtIndex:self.labelList.count-1] removeFromSuperview];
        
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+greenPhaseLength;
        
        UILabel *yellowLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,yellowPhaseLength,timingGraphHeight)] autorelease];
        yellowLabel.backgroundColor = [UIColor yellowColor];      
        
        [self.labelList addObject:yellowLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+yellowPhaseLength;
        
        UILabel *allRedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing2GraphPositionX,timingGraphPositionY,allRedPhaseLength,timingGraphHeight)] autorelease];
        allRedLabel.backgroundColor = [UIColor redColor];      
        
        [self.labelList addObject:allRedLabel];
        [self.view addSubview:[self.labelList objectAtIndex:self.labelList.count-1]];
        self.timingRing2GraphPositionX=self.timingRing2GraphPositionX+allRedPhaseLength;
    }
    {
        UILabel *barrierLabel = [[[UILabel alloc] initWithFrame:CGRectMake(barrierPositionX,timingGraphPositionY,5,timingGraphHeight)] autorelease];
        barrierLabel.backgroundColor = [UIColor blackColor];
        [self.labelList addObject:barrierLabel];
        [self.view addSubview:barrierLabel];
    }
    int offsetLabelPositionX=round(300*self.offsetPhaseTime/[self.signal.cycleLength intValue]);
    UILabel *offsetLabel = [[[UILabel alloc] initWithFrame:CGRectMake(TIMING_RING2_GRAPH_INITIAL_POSITION_X+offsetLabelPositionX,TIMING_RING1_GRAPH_POSITION_Y,2,50)] autorelease];
    offsetLabel.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:offsetLabel];
    
    UIImageView *offsetTriangle=[[[UIImageView alloc] initWithFrame:CGRectMake(TIMING_RING2_GRAPH_INITIAL_POSITION_X+offsetLabelPositionX-8, TIMING_RING1_GRAPH_POSITION_Y+50, 16, 16)] autorelease];
    [offsetTriangle setImage:[UIImage imageNamed:@"offset_triangle.png"]];
    [self.view addSubview:offsetTriangle];
    
    UILabel *offsetValueLabel = [[[UILabel alloc] initWithFrame:CGRectMake(TIMING_RING2_GRAPH_INITIAL_POSITION_X+offsetLabelPositionX-8+16+5,TIMING_RING1_GRAPH_POSITION_Y+50,80,16)] autorelease];
    offsetValueLabel.text=[NSString stringWithFormat:@"Offset:%@",self.signal.offset];
    offsetValueLabel.textColor=[UIColor orangeColor];
    offsetValueLabel.font = [UIFont boldSystemFontOfSize:14.0];
//    [offsetValueLabel setFont:[Utils getSystemFontWithSize:12]];
    offsetValueLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:offsetValueLabel];
    
    
}
- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    

}
-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController setToolbarHidden:NO];
    [super viewWillAppear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    double lastDistance=[userDefaults doubleForKey:@"lastDistance"];
    [userDefaults setDouble:1000 forKey:@"lastDistance"];
    [self updateLabels];
}
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!self.signal) {
        return;
    }
    if (self.signal.cycleLength==0) {
        return;
    }
    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    self.automaticPlayOrNot=[userDefaults boolForKey:@"automaticPlayOrNot"];
    
    if (self.automaticPlayOrNot) {
        [self.locationManager startUpdatingLocation];
        [self setStartStopButton:YES];
    }else
    {
//        [self.locationManager stopUpdatingLocation];
        [self setStartStopButton:NO];
    }
    
    
}
-(void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}


- (void) addLabelResponder:(UILabel *) label 
{
    [label setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickLabel:)];
    [tapGestureRecognizer setNumberOfTapsRequired:1];
    [label addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    UIPanGestureRecognizer *dragGesture = [[[UIPanGestureRecognizer alloc] 
                                            initWithTarget:self 
                                            action:@selector(labelDragged:)] autorelease];
    
	[label addGestureRecognizer:dragGesture];
}
- (void) updateTimer:(id) sender {
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] offSet:([self.signal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    [self updateRealTimeInformation];
    
    {
        self.timingRing1GraphPositionX=TIMING_RING1_GRAPH_INITIAL_POSITION_X;
        self.timingRing2GraphPositionX=TIMING_RING2_GRAPH_INITIAL_POSITION_X;
        int timingGraphPositionY=TIMING_RING1_GRAPH_POSITION_Y;
        int timingGraphHeight=TIMING_RING1_GRAPH_HEIGHT;
        
        int cycleLabelLength=controllerTimer*300/[self.signal.cycleLength intValue];
        [self.cycleLabel removeFromSuperview];
        self.cycleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.timingRing1GraphPositionX,timingGraphPositionY-10,cycleLabelLength,5)] autorelease];
//        self.cycleLabel.frame.size.width=cycleLabelLength
        
        _cycleLabel.backgroundColor = [UIColor blueColor];
        _cycleLabel.textColor=[UIColor darkGrayColor];
        [self.view addSubview:self.cycleLabel];
    }
    
   




}
- (void) initRealTimeInformation
{
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] offSet:([self.signal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    int cycleTimer=controllerTimer;
    if (self.SignalTimerLabel) {
        
        
        self.SignalTimerLabel.text=[NSString stringWithFormat:@"Controller Timer: %d/%@",controllerTimer,self.signal.cycleLength];
    }
    
    
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
        //        [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
        if (cycleTimer<=[phase.greenTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:0];
           
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:1];
            
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            break;
        }
        
        
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        
    }
    
    
    cycleTimer=controllerTimer;
    
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        
        if (cycleTimer<=[phase.greenTime doubleValue]) {
            
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:0];
            
            break;
            
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:0];
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
            }
            [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:0];
            break;
        }
        
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        //            self.Ring2CurrentPhaseLabel.text=@"NO Phase";
    }
    //        Phase 1 NBT Green 15/35
    //    }
    self.lastMainCountDownNumber=[self.mainCountDownLabel.text intValue];
}
- (void) updateRealTimeInformation
{
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] offSet:([self.signal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    int cycleTimer=controllerTimer;
    if (self.SignalTimerLabel) {
        
        
        self.SignalTimerLabel.text=[NSString stringWithFormat:@"Controller Timer: %d/%@",controllerTimer,self.signal.cycleLength];
    }
    
    
    for (int i=0; i<self.signal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring1.phaseList objectAtIndex:i];
//        [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
        if (cycleTimer<=[phase.greenTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:0];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:0];
            }
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:1];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:1];
            }
            
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring1.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:1 color:2];
            }
            break;
        }
        
        
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        
    }
    
    
    cycleTimer=controllerTimer;
    
    for (int i=0; i<self.signal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.signal.ring2.phaseList objectAtIndex:i];
        
        if (cycleTimer<=[phase.greenTime doubleValue]) {
            
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:0];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:0];
            }
            
            break;
            
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:1];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:1];
            }
            break;
        }
        if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            
            if ([self.mainCountDownLabel.text intValue]>(([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer)) {
                self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            }
            self.mainCountDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            if (self.lastMainCountDownNumber<[self.mainCountDownLabel.text intValue]) {
                for (int j=0; j<self.signal.ring2.phaseList.count; j++) {
                    [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
                }
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
            }
            if ([self.mainCountDownLabel.text intValue]<=6) {
                [self.dynamicIntersectionView setPhaseImageColor:phase.phaseID ring:2 color:2];
            }
            break;
        }
        
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        //            self.Ring2CurrentPhaseLabel.text=@"NO Phase";
    }
    //        Phase 1 NBT Green 15/35
    //    }
    self.lastMainCountDownNumber=[self.mainCountDownLabel.text intValue];
    
}

- (IBAction)clickNextButton:(id)sender
{
    if (self.signalIndex>=self.signalList.count-1) {
        return;
    }
    
    CATransition* trans = [CATransition animation];
    [trans setDuration:0.5];
    [trans setType:kCATransitionReveal];
    [trans setSubtype:kCATransitionFromTop];
    [trans setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    SignalDetailViewController *nextSignalDetailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:self.signalIndex+1 automaticPlayOrNot:self.automaticPlayOrNot bundle:nil] autorelease];
    UINavigationController * parentController=self.navigationController;
    
    [parentController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController popViewControllerAnimated:NO];

     [nextSignalDetailViewController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController pushViewController:nextSignalDetailViewController animated:NO];
    
    
   

    
    
    
    
}

- (IBAction)clickLastButton:(id)sender {
    if (self.signalIndex<=0) {
        return;
    }
    
    CATransition* trans = [CATransition animation];
    [trans setDuration:0.5];
    [trans setType:kCATransitionMoveIn];
    [trans setSubtype:kCATransitionFromBottom];
    [trans setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    
    SignalDetailViewController *lastSignalDetailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:self.signalIndex-1 automaticPlayOrNot:self.automaticPlayOrNot bundle:nil] autorelease];
    UINavigationController * parentController=self.navigationController;
     self.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [parentController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController popViewControllerAnimated:NO];
    [lastSignalDetailViewController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController pushViewController:lastSignalDetailViewController animated:NO];
}

- (void)pageSlided:(UIPanGestureRecognizer *)gesture
{
	UIView *view = (UIView *)gesture.view;

	CGPoint translation = [gesture translationInView:view];
    
    if (translation.y>10) {
        [self clickLastButton:nil];
    }
    if (translation.y<-10) {
        [self clickNextButton:nil];
    }
	// move label
	
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) goToEditSignal:(id)sender
{
    SignalAssistorDetailEditViewController *detailViewController=[[[SignalAssistorDetailEditViewController alloc] initWithNibNameAndSignal:@"SignalAssistorDetailEditViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signal:self.signal bundle:nil] autorelease];
    [detailViewController setTitle:@"Edit Signal"];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void) setStartStopButton:(BOOL)startorstop
{
    UIBarButtonItem *startStopButton = nil;
    if (startorstop == YES) {
        startStopButton = [[[UIBarButtonItem alloc]     initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(startStopAction:)] autorelease];
        
        [startStopButton setStyle:UIBarButtonSystemItemPause];
        
        
    }
    else
    {
        startStopButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startStopAction:)] autorelease];
        [startStopButton setStyle:UIBarButtonSystemItemPlay];
    }
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    
    
//    [playButton setStyle:UIBarButtonSystemItemPause];
    
    
    UIBarButtonItem *editSignalButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(goToEditSignal:)] autorelease];
//    UIBarButtonItem *timeSpaceButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(goToTimeSpace:)] autorelease];
//    UIBarButtonItem *timeSpaceHistoryButton=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(goToTimeSpaceHistory:)] autorelease];
    CustomizedBarButtonItem *timeSpaceButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIcon.png"] target:self action:@selector(goToTimeSpace:)] autorelease];
    //    [playButton setStyle:UIBarButtonSystemItemPause];
    
    CustomizedBarButtonItem *timeSpaceHistoryButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIconHistory.png"] target:self action:@selector(goToTimeSpaceHistory:)] autorelease];
    
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    
    
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,startStopButton,space,timeSpaceButton,space,timeSpaceHistoryButton,space,editSignalButton,nil ];
}
- (IBAction)startStopAction:(id)sender
{
    if (self.automaticPlayOrNot) {
        self.automaticPlayOrNot=NO;
        [self setStartStopButton:false];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        [userDefaults setBool:NO forKey:@"automaticPlayOrNot"];
        
        [self.locationManager stopUpdatingLocation];
    }
    else{
        self.automaticPlayOrNot=YES;
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        [userDefaults setBool:YES forKey:@"automaticPlayOrNot"];
        [self setStartStopButton:true];
        DirectionSelectionPopupViewController *directionSelection=[[DirectionSelectionPopupViewController alloc] init:self.locationManager]  ;
        [self.view addSubview:directionSelection.view];
//        [self.locationManager startUpdatingLocation];
    }
    
    
}

- (IBAction)goToTimeSpace:(id)sender
{
    TimeSpaceViewController *timeSpaceViewController=[[[TimeSpaceViewController alloc] initWithNibName:@"TimeSpaceViewController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:self.signal direction:NORTHBOUND] autorelease];
    [timeSpaceViewController setTitle:@"Time Space"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:timeSpaceViewController animated:YES];
}
- (IBAction)goToTimeSpaceHistory:(id)sender
{
    GPSRecordListController *gpsRecordListController=[[[GPSRecordListController alloc] initWithNibName:@"GPSRecordListController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:self.signal] autorelease];
    [gpsRecordListController setTitle:@"GPS Record List"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:gpsRecordListController animated:YES];
}

/*
 - (void) setStartStopButton:(BOOL)startorstop
 {
 UIBarButtonItem *startStopButton = nil;
 if (startorstop == YES) {
 startStopButton = [[UIBarButtonItem alloc]     initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(startStopAction:)];
 }
 else
 {
 startStopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startStopAction:)];
 }
 self.navigationItem.rightBarButtonItem = startStopButton;
 [startStopButton release];
 }
 
 - (IBAction)startStopAction:(id)sender
 {
 if (task.isActive)
 {
 [task stopTask];
 }
 else
 {
 [task startTask];
 }
 [self setStartStopButton:task.isActive];
 }
 */

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    double distance=[GeometryCalculation distanceOfTwoCoordinates:self.locationManager.location.coordinate coordB:self.intersection.intersectionCoordinate];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double lastDistance=[userDefaults doubleForKey:@"lastDistance"];
    [userDefaults setDouble:distance forKey:@"lastDistance"];
    self.automaticDirection=[userDefaults boolForKey:@"automaticDirection"];
    CLLocationDirection direction=[userDefaults doubleForKey:@"direction"];
    if (self.automaticDirection) {
        direction=self.locationManager.heading.magneticHeading;
    }
//    [self automaticNextSignal:self.locationManager.location.coordinate direction:direction signalList:self.signalList];
    if (distance-lastDistance>=2) {
//    counter=counter+1;
//    if (counter==5) {
//        counter=0;
        [self automaticNextSignal:self.locationManager.location.coordinate direction:direction signalList:self.signalList];
//    }
    
    }
}
- (void)automaticNextSignal:(CLLocationCoordinate2D) currentLocation direction:(CLLocationDirection) direction signalList:(NSArray *) signalList
{
    
    if (self.signalIndex>self.signalList.count-1) {
        return;
    }
    
    CATransition* trans = [CATransition animation];
    [trans setDuration:0.5];
    [trans setType:kCATransitionReveal];
    [trans setSubtype:kCATransitionFromTop];
    [trans setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    int nextSignalIndex=[GeometryCalculation calculateNextSignalIndex:self.signalList newHeading:direction coordinate:self.intersection.intersectionCoordinate agency:self.agency subSystem:self.subSystem];
    
    if (nextSignalIndex==-1||nextSignalIndex==self.signalIndex) {
        return;
    }
   SignalDetailViewController *nextSignalDetailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:nextSignalIndex automaticPlayOrNot:self.automaticPlayOrNot bundle:nil] autorelease];
//    self.signal=[self.signalList objectAtIndex:nextSignalIndex];
//    self.intersection=[XMLParser getIntersection:self.signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    
    UINavigationController * parentController=self.navigationController;
    
    [parentController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController popViewControllerAnimated:NO];
    
//    [nextSignalDetailViewController.view.layer addAnimation:trans forKey:kCATransition];
    [parentController pushViewController:nextSignalDetailViewController animated:NO];
    
    
    
    
    
    
    
    
}

- (IBAction)clickLabel:(id)sender
{
    if (!self.adjustTimeBool) {
        return;
    }
    UITapGestureRecognizer *tapGesture=(UITapGestureRecognizer *)sender;
    UIView *label=tapGesture.view;
    
    NSArray *ring1PhaseList=self.signal.ring1.phaseList;
    NSArray *ring2PhaseList=self.signal.ring2.phaseList;
    NSLog(@"\nlabel.tag= %d\n", label.tag);
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.signal.cycleLength intValue] offSet:([self.signal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    if (100<=label.tag && label.tag<300) {
        if (label.tag<200) {
            int index=label.tag-100;
            double timeToBegin=0;
            for (int i=0; i<index; i++)
            {
                SignalPhase *phase=[ring1PhaseList objectAtIndex:i];
                timeToBegin=timeToBegin+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
                
            }
            int baseTimeOffset=(int)(timeToBegin-controllerTimer)+[self.agency.baseTimeOffset integerValue];
            self.agency.baseTimeOffset=[NSString stringWithFormat:@"%d",baseTimeOffset];
            [XMLParser updateAgency:self.agency];
            
        }else
        {
            int index=label.tag-200;
            double timeToBegin=0;
            for (int i=0; i<index; i++)
            {
                SignalPhase *phase=[ring2PhaseList objectAtIndex:i];
                timeToBegin=timeToBegin+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
                
            }
            int baseTimeOffset=(int)(timeToBegin-controllerTimer)+[self.agency.baseTimeOffset integerValue];
            self.agency.baseTimeOffset=[NSString stringWithFormat:@"%d",baseTimeOffset];
            [XMLParser updateAgency:self.agency];
            
        }
    }
    
}

- (IBAction)clickTimeAdjustButton:(id)sender
{
    if (self.adjustTimeBool) {
        self.adjustTimeBool=NO;
//        [self.timeAdjustButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [self.timeAdjustButton setBackgroundColor:[UIColor clearColor]];
    }else
    {
        self.adjustTimeBool=YES;
        [self.timeAdjustButton setBackgroundColor:[UIColor redColor]];
    }
}


@end
